package com.py.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.common.constants.WemediaConstants;
import com.py.common.constants.WmNewsMessageConstants;
import com.py.common.exception.CustomException;
import com.py.model.common.dtos.PageResponseResult;
import com.py.model.common.dtos.ResponseResult;
import com.py.model.common.enums.AppHttpCodeEnum;
import com.py.model.wemedia.dtos.WmNewsDto;
import com.py.model.wemedia.dtos.WmNewsPageReqDto;
import com.py.model.wemedia.pojos.WmMaterial;
import com.py.model.wemedia.pojos.WmNews;
import com.py.model.wemedia.pojos.WmNewsMaterial;
import com.py.utils.common.WmThreadLocalUtil;
import com.py.wemedia.mapper.WmNewsMapper;
import com.py.wemedia.mapper.WmNewsMaterialMapper;
import com.py.wemedia.service.AutoScanService;
import com.py.wemedia.service.WmMaterialService;
import com.py.wemedia.service.WmNewsService;
import com.py.wemedia.service.WmTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialService wmMaterialService;
    @Resource
    private WmNewsMaterialMapper newsMaterialMapper;
    @Autowired
    private AutoScanService autoScanService;
    @Autowired
    private WmTaskService taskService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    /**
     * 分页查询
     *
     * @param reqDto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto reqDto) {
        //参数校验
        reqDto.checkParam();

        IPage page = new Page(reqDto.getPage(), reqDto.getSize());
        //构造查询参数
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.get().getId());
        queryWrapper.eq(reqDto.getStatus() != null, WmNews::getStatus, reqDto.getStatus());

        queryWrapper.eq(reqDto.getChannelId() != null, WmNews::getChannelId, reqDto.getChannelId());
        queryWrapper.like(!StringUtils.isEmpty(reqDto.getKeyword()), WmNews::getTitle, reqDto.getKeyword());

        if (reqDto.getBeginPubDate() != null && reqDto.getEndPubDate() != null) {
            queryWrapper.between(WmNews::getCreatedTime, reqDto.getBeginPubDate(), reqDto.getEndPubDate());
        }
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page(page, queryWrapper);

        ResponseResult result = new PageResponseResult(reqDto.getPage(), reqDto.getSize(), (int) page.getTotal());

        result.setData(page.getRecords());
        return result;
    }

    /**
     * 文章审核总方法
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //参数校验
        checkParam(wmNewsDto);
        String originalContent = wmNewsDto.getContent();
        List<Map> maps = JSON.parseArray(originalContent, Map.class);
        maps = maps.stream().limit(maps.size() - 1).collect(Collectors.toList());
        wmNewsDto.setContent(JSON.toJSONString(maps));
        //修改或者保存
        WmNews wmNews = saveOrUpdate(wmNewsDto);
        //判断文章状态如果是草稿,则直接返回
        if (wmNews.getStatus() == WmNews.Status.NORMAL.getCode()) {
            return ResponseResult.okResult(null);
        }
        //获取正文中所有的图片
        List<String> pics = getPictures(wmNewsDto.getContent());
        saveRelations(pics, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);

        //保存封面和素材的关系
        saveRelationsByCover(pics, wmNewsDto, wmNews);
        if (wmNews.getPublishTime() != null) {
            taskService.addTask(wmNews);
        } else {
            autoScanService.scan(wmNews.getId());
        }

        return ResponseResult.okResult(null);
    }

    /**
     * 文章上下架
     *
     * @param Dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto Dto) {
        //参数校验
        if (Dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询文章
        WmNews wmNews = getById(Dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //查询文章状态是否是已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章未发布,不能进行上下架");
        }
        //修改文章上下架状态
        if (Dto.getEnable() != null && Dto.getEnable() > -1 && Dto.getEnable() < 2) {
            wmNews.setEnable(Dto.getEnable());
            updateById(wmNews);


            if (wmNews.getArticleId() != null) {
                //发送消息通知article修改上下架配置
                HashMap<String, Object> map = new HashMap<>();
                map.put("articleId", wmNews.getArticleId());
                map.put("enable", wmNews.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }

        }

        return ResponseResult.okResult("上下架成功");
    }


    /**
     * 草稿文章回显
     *
     * @param newId
     * @return
     */
    @Override
    public ResponseResult echo(int newId) {
        WmNews wmNews = getById(newId);
        WmNewsDto newsDto = null;
        if (wmNews != null) {
            newsDto = new WmNewsDto();
            BeanUtils.copyProperties(wmNews, newsDto);
        }
        return ResponseResult.okResult(wmNews);
    }


    /**
     * 删除文章
     *
     * @param newId
     * @return
     */
    @Override
    public ResponseResult deleteNews(int newId) {
        WmNews wmNews = getById(newId);
        if (wmNews.getEnable().equals(1)) {
            //文章已上架,不能删除
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "请先下架文章");
        }
        //删除文章
        removeById(newId);

        return ResponseResult.okResult("删除成功");
    }


    /**
     * 封面和素材的关系
     *
     * @param pics
     * @param newsDto
     * @param wmNews
     */
    private void saveRelationsByCover(List<String> pics, WmNewsDto newsDto, WmNews wmNews) {
        List<String> images = newsDto.getImages();
        //如果封面样式为自动
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(newsDto.getType())) {
            int size = pics.size();
            //图片大于三张则三图
            if (size >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = pics.stream().limit(3).collect(Collectors.toList());
            } else if (size >= 1 && size < 3) {
                //图片大于1张小于3张则1图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = pics.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(StringUtils.collectionToCommaDelimitedString(images));
            }
            updateById(wmNews);
        }

        if (!CollectionUtils.isEmpty(images)) {
            saveRelations(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }


    /**
     * 保存素材和文章的关系
     *
     * @param pics   文章内容图片
     * @param newsId 自媒体文章id
     */
    private void saveRelations(List<String> pics, Integer newsId, Short type) {
        if (CollectionUtils.isEmpty(pics)) {
            log.info("图片集合为空");
            return;
        }
        List<WmMaterial> list = wmMaterialService.list(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, pics));
        if (CollectionUtils.isEmpty(list)) {
            log.info("素材失效,查询自媒体失败");
            return;
        }
        List<Integer> ids = list.stream().map(WmMaterial::getId).collect(Collectors.toList());
        newsMaterialMapper.saveRelations(ids, newsId, type);
    }


    /**
     * 从正文中获取图片素材
     *
     * @param content
     * @return
     */
    private List<String> getPictures(String content) {
        List<String> pics = new ArrayList<>();
        List<Map> mapList = JSON.parseArray(content, Map.class);
        for (Map map : mapList) {
            if ("image".equals(map.get("type"))) {
                pics.add((String) map.get("value"));
            }
        }
        return pics;
    }


    /**
     * 保存或者修改文章
     *
     * @param wmNewsDto
     * @return
     */
    private WmNews saveOrUpdate(WmNewsDto wmNewsDto) {
        WmNews news = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, news);
        news.setUserId(WmThreadLocalUtil.get().getId());
        //封面图片转换aaa.jpg,bb.jpg
        if (!CollectionUtils.isEmpty(wmNewsDto.getImages())) {
            news.setImages(StringUtils.collectionToCommaDelimitedString(wmNewsDto.getImages()));
        }
        news.setCreatedTime(new Date());
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())) {
            news.setType(null);
        }
        if (wmNewsDto.getId() == null) {
            save(news);
        } else {
            //有id是修改 删除文章和素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNewsDto.getId()));
            //根据id修改
            updateById(news);
        }

        return news;
    }

    /**
     * 参数校验
     *
     * @param newsDto
     */
    private void checkParam(WmNewsDto newsDto) {
        if (StringUtils.isEmpty(newsDto.getTitle())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (StringUtils.isEmpty(newsDto.getContent())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
